<?php

namespace apiend\modules\course\controllers;

use Yii;
use apiend\components\Controller;
use common\models\course\RecommendCourse;
use common\models\school\School;
use common\helpers\ArrayHelper;
use common\models\course\Course;

/**
 * 课程模块默认首页
 * Default controller for the `course` module
 */
class DefaultController extends Controller {

    public $modelClass = 'api\modules\course\models\RecommendCourseSearch';

    /**
     * {@inheritdoc}
     */
    public function actions() {
        return [
            'view' => [
                'class' => 'yii\rest\ViewAction',
                'modelClass' => $this->modelClass,
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actionIndex() {
        $area = Yii::$app->request->get('area');

        $query = RecommendCourse::find()
        ->alias('t')
        ->where([
            'and',
            ['t.status' => RecommendCourse::STATUS_ACTIVE],
            ['!=', 't.category_id', 0],
        ])
        ->orderBy([
            't.category_id' => SORT_ASC,
            't.listorder' => SORT_ASC,
            't.updated_at' => SORT_DESC,
        ]);

        if ($area) {
            $schools = School::find()->where(['district' => $area])->all();
            $schoolids = ArrayHelper::getColumn($schools, 'id');
            $query->joinWith('course c', true, 'INNER JOIN');

            $query->andWhere([
                'c.school_id' => $schoolids,
                'c.status' => Course::STATUS_ACTIVE,
                'c.audit_status' => Course::AUDIT_STATUS_ACTIVE,
            ]);
        }

        $data = $query->all();

        $result = [];
        $category = [];
        foreach ($data as $item) {
            if (!isset($result[$item->category_id])) {
                $result[$item->category_id] = [
                    'id' => (int) $item->category_id,
                    'name' => $item->category->name,
                    'recommends' => []
                ];
                $category[$item->category_id] = 0;
            }
            $category[$item->category_id] ++;

            if ($category[$item->category_id] <= 5) {
                $result[$item->category_id]['recommends'][] = $item->toArray([
                    'id',
                    'title',
                    'banner',
                    'thumb',
                    'listorder',
                ], [
                    'link',
                    'banner',
                    'thumb',
                ]);
            }
        }

        foreach ($category as $cid => $cnums) {
            if ($cnums % 2 == 0) {
                ArrayHelper::remove($result, $cid);
            }
        }

        return array_values($result);
    }

}
